# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  before_filter :set_charset,:active_user
  helper :application
  session_times_out_in 600, :after_timeout => :timeout_authorize, :before_timeout=> :reset_user
  
  def timeout_authorize
    logger.info "HELLO, IVE TIMED OUT!"
  end
  
  def set_charset
    headers["Content-Type"] = "text/html; charset=UTF-8"
  end
  
  #active user
  def active_user
    control_name=params[:control]||"index"
    action_name=params[:action]||"index"
    obj_id=params[:id]||"0"
    @activeuser=ActiveUser.active_user(session[:active_user_id],request.env["REMOTE_HOST"])
    @activeuser.log_action(control_name,action_name,obj_id.to_i)
    session[:active_user_id]=@activeuser.id
  end
  
  #clear activeuser session
  def remove_session
    reset_user
    reset_session
  end
  
  def reset_user
    ActiveUser.remove_active_user(session[:active_user_id])
  end
  
  private 
  def error_messages_of(object)
    ret=[]
    object.errors.each  { |error| text<<['<li>'+error[1].to_s+'</li>']} if object && !object.errors.empty?
    return ret=[]
  end
  
  def user_authorize
    flash[:notice]=["请用注册用户登陆"]
    if @activeuser.guest?
    if request.xhr?
          render :update do |page|
            page.redirect_to :controller => "login", :action=>"login"
          end
        else
          redirect_to :controller => "login", :action=>"login"
        end
    end
  end
  
  def admin_authorize
    flash[:notice]=["请以管理员账号登陆"]
    if @activeuser.user.administrative
        if request.xhr?
          render :update do |page|
            page.redirect_to :controller => "login", :action=>"login"
          end
        else
          redirect_to :controller => "login", :action=>"login"
        end
    end
  end
  
end